from html.parser import HTMLParser
from common import Path
import time

class HTMLParser_LFCO_CL(HTMLParser):
    def __init__(self):
        self.data_list = []

        self.reset()
        self.table_found = False
        self.pause       = False

    def clear(self):
        self.data_list = []

        self.reset()
        self.table_found = False
        self.pause       = False

    def handle_starttag(self, tag, attrs):
        if tag == 'a' and attrs[0] == ('class', 'report'):
            self.pause = True

    def handle_endtag(self, tag):
        if tag == 'a':
            self.pause = False


    def handle_data(self, data):
        if data.isspace():
            return

        if 'No movement' in data:
            self.table_found = True

        elif self.table_found and not self.pause and not data in ['Win', 'Loss', 'Draw']:
            self.data_list.append(data)


class CLTableParser(HTMLParser):
    # noinspection PyMissingConstructor
    def __init__(self):
        self.parser = HTMLParser_LFCO_CL()
        self.parser.strict = True
        self.start_tag   =  'UEFA Champions League Table' # 'UEFA Champions League - Group B' #'Group B'
        self.end_tag     =   '</table>' # <div class="league-table full-table-wide">' # '<div class="mod ft ">' #'<!-- close the final table -->'
        self.club_rus_name = {'Real Madrid':'Реал Мадрид', 'Liverpool': 'Ливерпуль', 'Ludo Razgd': 'Людогорец', 'FC Basel': 'Базель',
                                'Juventus': 'Ювентус', 'Atl Madrid': 'Атлетико Мадрид', 'Malmö FF': 'Мальмо', 'Olympiakos': 'Олимпиакос',
                                'Zenit St P':'Зенит', 'Monaco': 'Монако', 'Bayer Levkn': 'Байер', 'Benfica': 'Бенфика',
                                'Bor Dortmd': 'Боруссия', 'Arsenal': 'Арсенал', 'Anderlecht': 'Андерлехт', 'Galatasaray': 'Галатасарай',
                                'Bayern Mun': 'Бавария', 'Roma': 'Рома', 'Man City': 'Ман. Сити', 'CSKA': 'ЦСКА',
                                'Paris St G': 'ПСЖ', 'Barcelona': 'Барселона', 'Ajax': 'Аякс', 'Apoel Nic': 'Апоэль',
                                'Chelsea': 'Челси', 'NK Maribor': 'Марибор', 'Schalke': 'Шальке', 'Sporting': 'Спортинг',
                                'FC Porto': 'Порто',  'BATE Bor': 'БАТЭ', 'Shakt Donsk': 'Шахтер', 'Ath Bilbao': 'Атлетик Бильбао'}


    def groups(self, source):

        while self.start_tag in source:
            start_pos   = source.find(self.start_tag)
            end_pos = start_pos + source[start_pos:].find(self.end_tag)
            assert start_pos > 0 and end_pos > 0, 'Tags not found'

            yield( source[start_pos : end_pos])
            source = source[end_pos:]

    def sanity_passed(self):
        return (len(self.parser.data_list) == 40)


    def parse_source(self, source):
        all_tables = []
        for group_table in self.groups(source):
            try:
                #print(group_table[:50])
                self.parser.clear()
                self.parser.feed(group_table)
            except:
                print ("Exception while parsing group table !\n", group_table[:50])

            if not self.sanity_passed():
                return

            if 'Liverpool' in self.parser.data_list:
                self.create_short_html(path.short_table)

            all_tables.append(self.make_lists())
        self.create_full_html(all_tables, path.full_cl_table)


    def parse_url(self, url):
        import urllib.request
        try:
            print ('Opening ', url)
            resp = urllib.request.urlopen(url).read()
            resp_dec = resp.decode('utf-8') #'iso-8859-1'))
            self.parse_source(resp_dec)
        except:
            print ("no data for url ", url)
            self.html = NULL


    def parse_file(self, input):
        print ('Opening ', input)
        with open(input, 'r', encoding = 'utf-8') as source_file:
            self.parse_source(source_file.read())



    def make_lists(self):
        #''' First item in the table is the part of the heading, so remove it '''
        #self.parser.data_list.pop(0)
        self.table_list = []
        len = 10
        for i in range(0,4):
            self.table_list.append(self.parser.data_list[i*len : (i+1)*len])

        #print(self.table_list)
        return self.table_list

    def create_short_html(self, output):
        self.make_lists()

        print ('Writing ', output)
        with open(output, 'a', encoding = 'utf-8') as out_file:
            out_file.write('\n<h2> Лига Чемпионов. Группа Б</h2> \n<table class="short-league-table"> <tbody>')

            for line in self.table_list:
                if line[1] == 'Liverpool':
                    out_file.write ('<tr class = \"liverpool-stats\">')
                else:
                    out_file.write ('<tr>')

                out_file.write ('<td class=\"club-info\">{0}.</td> <td class=\"club-info\">{1}</td><td class=\"total-stat-summary summary-stat\">{2}</td> </tr>\n'.\
                                format(line[0], self.club_rus_name[line[1]], line[9]))

            out_file.write(' </tbody></table> \n <small> <a href="http://www.liverbird.ru/cl_table">Вся таблица</a> </small>')


    def create_full_html(self, all_tables, output):
        g_id = (c for c in ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'])

        print ('Writing ', output)
        with open(output, 'w', encoding = 'utf-8') as out_file:
            out_file.write(' <h2> Лига Чемпионов 2014-2015</h2>')

            for table in all_tables:
                out_file.write('<h3> Группа {}</h3> <table class="cl-table">'.format(next(g_id)))
                out_file.write(' <thead><th>#</th> <th>Клуб</th> <th>Pl</th> <th>W</th> <th>D</th> <th>L</th> <th>F</th> <th>A</th> \
                                <th class=\"summary-stat\">GD</th> <th class=\"summary-stat\">Pts</th></thead> <tbody>')
                for line in table:
                    line[1] = self.club_rus_name[line[1]]

                    if line[1] == 'Ливерпуль':
                        out_file.write ('<tr class = \"liverpool-stats\">')
                    else:
                        out_file.write ('<tr>')

                    out_file.write ('<td class=\"club-info\">{0}.</td> <td class=\"club-info\">{1}</td>\
                                    <td class=\"stat\">{2}</td><td class=\"stat\">{3}</td><td class=\"stat\">{4}</td>\
                                    <td class=\"stat\">{5}</td><td class=\"stat\">{6}</td><td class=\"stat\">{7}</td>\
                                    <td class=\"summary-stat\">{8}</td> <td class=\"summary-stat\">{9}</td>  </tr>'.\
                                    format(*line))

                out_file.write('</tbody></table> ')

            out_file.write("<small>Обновлено {0.tm_year}/{0.tm_mon}/{0.tm_mon} в {0.tm_hour:02}:{0.tm_min:02} по Гринвичу</small>".format(time.gmtime()))




''' Main '''
import sys
if len(sys.argv) == 2 and sys.argv[1] == 'local':
    local = True
else:
    local = False

path = Path(local)
cl_table = CLTableParser()
cl_table.parse_url(path.bbc_cl_table_source)
